package com.qf.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author 常肖飞先生
 * @version V1.0
 * @Project day41_2
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/11 17:12
 */
@WebServlet(name = "MyContextServlet3",urlPatterns = "/context3")
public class MyContextServlet3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //作用-2. ServletContext 对象 当前java应用程序的执行环境上下文的对象。
        //获取上下文的路径。
        ServletContext app = this.getServletContext();
        String contextPath = app.getContextPath();
        System.out.println(contextPath);///day41
        //通过request对象获取程序的上下文路径
        System.out.println(request.getContextPath());//day41

        //还可以获取发布的项目的真实路径,，读取WEB-INF 中的内容。
//        C:\Users\Hou\IdeaProjects\day41_2\out\artifacts\day41_2_war_exploded\+
        System.out.println(app.getRealPath(""));
        FileInputStream fis = new FileInputStream(app.getRealPath("") + "WEB-INF\\bg.jpg");
        byte[] buf = new byte[1000];
        int count = fis.read(buf);
        while(count != -1){
            response.getOutputStream().write(buf,0,count);
            count = fis.read(buf);
        }
        fis.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
